package zl.osimall.manager.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import zl.osimall.common.bean.Admin;
import zl.osimall.common.bean.RespBean;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.service.AdminService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/api/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;


    @ResponseBody
    @PostMapping("/login")
    public RespBean login(String username,String password,
                          String captchaInput, HttpSession session) throws SteduException {
        System.out.println(session.getAttribute("captcha")+"         "+captchaInput);
        if(!captchaInput.equalsIgnoreCase((String) session.getAttribute("captcha"))){
            throw new SteduException("验证码错误");
        }

        Admin admin = adminService.login(username, password);
        session.setAttribute("admin", admin);
        return RespBean.ok("登录成功");

    }

    @PutMapping
    @ResponseBody
    public RespBean update(@RequestBody Admin admin, HttpSession session) throws SteduException {
        Admin newAdmin = adminService.update(admin);
        session.setAttribute("admin", newAdmin);
        return RespBean.ok("修改成功");
    }


    @GetMapping("/logout")
    @ResponseBody
    public RespBean logout(HttpSession session){
        session.invalidate();
        return RespBean.ok("注销成功");
    }


    @ResponseBody
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        //创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 10);

        //将验证码文本存放在session中
        session.setAttribute("captcha", captcha.getCode());

        //发送验证码图片到浏览器
        captcha.write(response.getOutputStream());
    }

    @ResponseBody
    @GetMapping("/info")
    public RespBean info(HttpSession session){
        Object admin = session.getAttribute("admin");
        return RespBean.ok("",admin);
    }
}
